package cn.websocket.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.websocket.mapper.UserMapper;
import cn.websocket.pojo.config.SaTokenProperties;
import cn.websocket.pojo.User;
import cn.websocket.service.UserService;
import cn.websocket.utils.RedisUtils;
import cn.websocket.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import static cn.websocket.constant.StatusConstant.*;

/**
 * <h3>WebSocket</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-08-18 14:05:48
 */
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class UserServcieImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final UserMapper userMapper;
    private final SaTokenProperties saTokenProperties;
    private final RedisUtils redisUtils;
    //登录逻辑
    @Override
    public Result<Object> login(User user, HttpSession httpSession) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getPhone, user.getPhone());
        User user_now = userMapper.selectOne(queryWrapper);
        if (user_now == null) return Result.fail(USER_NOT_FOUND);
        String text2 = SaSecureUtil.aesDecrypt(saTokenProperties.getVerifyKey(), user_now.getUserPassword());
        if(text2.equals(user.getUserPassword())){
            StpUtil.login(user_now.getPhone(),new SaLoginModel()
                    .setDevice("PC")
                    .setIsLastingCookie(false)
                    .setTimeout(60 * 60 * 24 * 1) //一天就行
                    .setIsWriteHeader(false)
            );
            user_now.setUserPassword(null);
            httpSession.setAttribute(HTTP_SESSION_CURRENTUSER, user_now);
            return Result.success(StpUtil.getTokenInfo());
        }else {
            return Result.fail(USER_PASSWORD_ERROR);
        }
    }

    //注册
    @Override
    public Result<Object> register(HttpServletRequest request,User user) {
        // 使用IP+时间戳作为Key，更稳定
        String clientIp = request.getRemoteAddr();
        long minuteTimestamp = System.currentTimeMillis() / 120000;
        String redisKey = CODE_REGISTER + clientIp + ":" + minuteTimestamp;
        String codeOld = (String) redisUtils.get(redisKey);
        if(codeOld == null) return Result.fail(CODE_LAPSE);
        if(!codeOld.equals(user.getCode())) return Result.fail(CODE_ERROR);
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,user.getPhone());
        User user1 = userMapper.selectOne(wrapper);
        if(user1 != null) return Result.fail(PHONE_REPEAT);
        String password = SaSecureUtil.aesEncrypt(saTokenProperties.getVerifyKey(), user.getUserPassword());
        user.setUserPassword(password);
        int insert = userMapper.insert(user);
        return insert>0?Result.success(USER_REGISTER_SUCCESS):Result.fail(USER_REGISTER_ERROR);
    }

    /**
     * 获取用户信息
     * @param httpSession
     * @return
     */
    @Override
    public Result<User> getUser(HttpSession httpSession) {
        User user = (User) httpSession.getAttribute(HTTP_SESSION_CURRENTUSER);
        System.out.println(user);
        return Result.success(user);
    }
}
